package net.knightwatch.kwtools;

import java.util.ArrayList;

import net.knightwatch.kwtools.database.KwToolsDatasource;
import net.knightwatch.kwtools.walkthrough.Potential;
import net.knightwatch.kwtools.walkthrough.PotentialArrayAdapter;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

public class PotentialListActivity extends ListActivity {
	
	ArrayList<Potential> potentials;
	PotentialArrayAdapter potentialAdapter;
	KwToolsDatasource datasource;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		datasource = new KwToolsDatasource(this);
		potentials = new ArrayList<Potential>();
		potentialAdapter = new PotentialArrayAdapter(this, R.layout.potential_list_item, potentials);
		this.setListAdapter(potentialAdapter);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		new UpdatePotentialsTask().execute();
	}
	private class UpdatePotentialsTask extends AsyncTask<Long, Void, Void>{

		@Override
		protected Void doInBackground(Long... params) {
			// Lookup the potentials in the database
			try{
				datasource.Open();
				potentials.clear();
				for(Potential p : datasource.getPotentials()){
					potentials.add(p);
				}
			} catch (Exception e){
				e.printStackTrace();
			} finally {
				datasource.Close();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Update the array adapter
			super.onPostExecute(result);
			potentialAdapter.notifyDataSetChanged();
		}
		
	}
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Potential potential = (Potential) l.getItemAtPosition(position);
		Intent intent = new Intent(PotentialListActivity.this, PotentialActivity.class);
		intent.putExtra("potentialId", potential.getId());
		intent.putExtra("customerId", potential.getCustomerId());
		intent.putExtra("readOnly", true);
		startActivity(intent);
	}
	
	

}
